package com.ks.test.app;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.util.HotSwapper;

public class Demo6 {

    //执行命令
    //java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=10240 Demo6
    public static void main(String[] args) throws Exception {
        HotSwapper hs = new HotSwapper(10240);
        new Hello().print();

        ClassPool classPool = ClassPool.getDefault();

        byte[] originBytes = classPool.get("com.ks.test.app.Hello").toBytecode();
        System.out.println("** reload a v2 version");

        CtClass ctClass = classPool.get("com.ks.test.app.Hello");
        ctClass.stopPruning(true);
        if(ctClass.isFrozen()){
            ctClass.defrost();
        }
        CtMethod ctMethod = ctClass.getDeclaredMethod("print");
        ctMethod.insertBefore("{System.out.println(\"** HelloWorld.print()\");}");
        hs.reload("com.ks.test.app.Hello", ctClass.toBytecode());

        new Hello().print();

        System.out.println("** reload the original version");

        hs.reload("com.ks.test.app.Hello", originBytes);
        new Hello().print();
    }

}
